<script setup>
import { inject, ref } from "vue";
// import stepsview from "../components/steps/steps.vue";
import { handleGoBack } from "@/utils/router";
import { orderlist, refundlist } from "@/services/order";
import { productdel, orderpay, productconfirm } from "@/services/pay";

import { uploadfile } from "@/services/upload";
import { onLoad, onShow, onReachBottom } from "@dcloudio/uni-app";
import { base_URL } from "@/utils/http";
import { mine, isPayPassApi, checkPayPass } from "@/services/user";
import { formatPrice } from "@/utils/formatPrice";

// import wxicon from "../static/icon_weixin.png";
// import yeicon from "../static/icon_yue.png";
// import dficon from "../static/icon_daifu.png";

import wxicon from "@/static/cloudlibrary/icon_weixin.png";
import yeicon from "@/static/cloudlibrary/icon_yue.png";
import dficon from "@/static/cloudlibrary/icon_daifu.png";

// const keyword = ref("");
const pages = ref({
  page: 1,
  limit: 20,
  status: -2,
  keyword: "",
});

const isrefund = ref(true);

const payform = ref({
  order_id: "",
});
const selectindex = ref(0);

const loading = ref(true);
const status = ref("more");
const listtabs = ref([
  { name: "全部", value: -2 },
  { name: "待付款", value: -1 },
  { name: "待自提", value: 0 },
  { name: "已完成", value: 3 },
  // { name: "售后", value: 4 },
]);
const current = ref(0);
const list = ref([]);
// 定义方法
function clicktabs(item) {
  pages.value.status = item.value;
  pages.value.page = 1;
  list.value = [];
  if (item.value == 4) {
    pages.value.status = "";
    isrefund.value = true;
    refundlistfun();
  } else {
    isrefund.value = false;
    getlist();
  }
}

//下拉触底
onReachBottom(() => {
  // 触发下拉触底时执行的操作
  if (pages.value.status == "") {
    // isrefund.value = true;
    // pages.value.status = "";
    refundlistfun();
  } else {
    // isrefund.value = false;
    getlist();
  }
});

onLoad((e) => {
  current.value = e.status;
  if (e.status == -2) {
    current.value = 0;
  } else if (e.status == -1) {
    current.value = 1;
  } else if (e.status == 0) {
    current.value = 2;
  } else if (e.status == 2) {
    current.value = 3;
  } else if (e.status == 3) {
    current.value = 4;
  } else if (e.status == 4) {
    current.value = 5;
  }
  if (e.status == 2) {
    pages.value.status = 3;
  } else {
    pages.value.status = e.status ? e.status : 0;
  }

  if (e.status == 4) {
    isrefund.value = true;
    pages.value.status = "";
    refundlistfun();
  } else {
    isrefund.value = false;
    getlist();
  }
});

onShow(() => {
  isPayPassFun();
});

async function refundlistfun() {
  loading.value = true;
  let res = await refundlist(pages.value);
  list.value = list.value.concat(res.data.list);
  if (res.data.list.length < pages.value.limit) {
    status.value = "no-more";
  } else {
    status.value = "more";
  }
  loading.value = false;
  if (res.data.list.length > 0) {
    pages.value.page = pages.value.page + 1;
  }
}

async function getlist() {
  loading.value = true;
  let res = await orderlist(pages.value);
  list.value = list.value.concat(res.data.list);

  if (res.data.list.length < pages.value.limit) {
    status.value = "no-more";
  } else {
    status.value = "more";
  }
  loading.value = false;
  if (res.data.list.length > 0) {
    pages.value.page = pages.value.page + 1;
  }
}

const searchfun = () => {
  pages.value.page = 1;
  // pages.value.keyword = "";
  list.value = [];
  if (pages.value.status == "") {
    // isrefund.value = true;
    // pages.value.status = "";
    refundlistfun();
  } else {
    // isrefund.value = false;
    getlist();
  }
};

const order_id = ref(0);
const index = ref(0);
const showOrder = ref(false);

const canlfun = (id, index1) => {
  showOrder.value = true;
  order_id.value = id;
  index.value = index1;
};

const closeOrder = () => {
  showOrder.value = false;
};

const orderSubmit = async () => {
  try {
    let res = await productdel({ order_id: order_id.value });
    if (res.code == 200) {
      uni.showToast({
        title: "订单已取消",
        icon: "none",
      });
      list.value.splice(index.value, 1);
      showOrder.value = false;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    showOrder.value = false;
  }
};

// 确认收货
const index2 = ref(0);
const showqrshfun = ref(false);
const closeqrshfun = () => {
  showqrshfun.value = false;
};

const qrshfun = (id, index) => {
  showqrshfun.value = true;
  order_id.value = id;
  index2.value = index;
};

const qrshfunSubmit = async () => {
  try {
    let res = await productconfirm({ order_id: order_id.value });
    if (res.code == 200) {
      uni.showToast({
        title: "已确认收货",
        icon: "none",
      });
      list.value.splice(index2.value, 1);
      showqrshfun.value = false;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    showqrshfun.value = false;
  }
};

const balance = ref(0);
// 查询用户余额
const mineFun = async () => {
  try {
    // 发送请求
    let res = await mine();
    if (res.code == 200) {
      balance.value = res.data.balance;
      if (balance.value < total_price.value) {
        pay_type.value = 2;
      }
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

//支付
const payshow = ref(false);
const total_price = ref(0);
const payfun = (item, index) => {
  selectindex.value = index;
  payform.value.order_id = item.order_id;
  total_price.value = item.total_price;
  payshow.value = true;
  mineFun();
};
const paylist = ref([
  {
    title: "2",
    des: "微信支付（推荐）",
    icon: wxicon,
  },
  {
    title: "1",
    des: "余额支付 ",
    icon: yeicon,
  },
  // {
  //   title: "7",
  //   des: "他人代付",
  //   icon: dficon,
  // },
]);
const close = () => {
  payshow.value = false;
  showqrshfun.value = false;
  showOrder.value = false;
  showPassword.value = false;
  focusinput.value = false;
  pay_pass.value = "";
};

const selectpayfun = async (type) => {
  if (balance.value < total_price.value && type == 1) {
    uni.showToast({
      title: "余额不足",
      icon: "none",
    });
    return;
  }
  pay_type.value = type;
};
// const qrshfun = async () => {};
const pay_type = ref(1);

function onBridgeReady(yishen, id) {
  WeixinJSBridge.invoke("getBrandWCPayRequest", yishen, (res) => {
    if (res) {
      getlist();
      // 使用以上方式判断前端返回,微信团队郑重提示：
      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
    }
  });
}

const isPayPass = ref(0);
const isPayPassFun = async () => {
  try {
    let res = await isPayPassApi();
    if (res.code == 200) {
      isPayPass.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const showPassword = ref(false);
const pay_pass = ref("");
const gopassword = () => {
  if (pay_type.value == 1 && isPayPass.value != 0) {
    showPassword.value = true;
    pay_pass.value = "";
    setTimeout(() => {
      focusinput.value = true;
    }, 500);
  } else if (pay_type.value == 1 && isPayPass.value == 0) {
    uni.showToast({
      title: "没有支付密码，前往设置",
      icon: "none",
    });

    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
      });
    }, 500);
  }
  if (pay_type.value == "2" || pay_type.value == "7") {
    gepaymentfun();
  }
};

const gocancle = () => {
  showPassword.value = false;
  pay_pass.value = "";
};
const ispay = ref(false);
const gepaymentfun = async () => {
  let res = null;
  try {
    if (pay_type.value == "1") {
      // 防止小程序输入密码重复支付
      if (!ispay.value) {
        ispay.value = true;
      } else {
        return;
      }

      res = await orderpay({
        ...payform.value,
        pay_type: 1,
        pay_pass: pay_pass.value,
      });
    }
    if (pay_type.value == "2") {
      // #ifdef H5 || APP-PLUS
      res = await orderpay({ ...payform.value, pay_type: 2 });
      let yishen = JSON.parse(res.data.wxWcPayData);

      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            onBridgeReady(yishen, payform.value),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent(
            "WeixinJSBridgeReady",
            onBridgeReady(yishen, payform.value)
          );
          document.attachEvent(
            "onWeixinJSBridgeReady",
            onBridgeReady(yishen, payform.value)
          );
        }
      } else {
        onBridgeReady(yishen, payform.value);
      }
      // #endif

      // #ifdef MP-WEIXIN
      let res = await orderpay({ ...payform.value, pay_type: 3 });
      if (res.code == 200) {
        // 仅作为示例，非真实参数信息。
        uni.requestPayment({
          provider: "wxpay",
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success: function (res) {
            uni.showToast({
              title: "支付成功",
              icon: "none",
            });
            getlist();
          },
          fail: function (err) {
            uni.showToast({
              title: "取消支付",
              icon: "none",
            });
          },
        });
      } else {
        uni.showToast({
          title: "支付失败",
          icon: "none",
        });
      }

      // #endif

      return;
    }
    if (pay_type.value == "7") {
      uni.navigateTo({
        url: "/pages/upgrade/payment/index?order_id=" + payform.value.order_id,
      });
      return;
    }

    if (res.code == 200) {
      uni.showToast({
        title: "支付成功",
        icon: "none",
      });
      list.value.splice(selectindex.value, 1);
      payshow.value = false;
      showPassword.value = false;
      focusinput.value = false;
    } else {
      pay_pass.value = "";
      uni.showToast({
        title: res.info,
        icon: "none",
      });
    }
  } catch (e) {
    ispay.value = false;
    if (typeof WeixinJSBridge == "undefined" && pay_type.value == "2") {
      uni.showToast({
        title: "暂未开通微信支付！",
        icon: "none",
      });
      return;
    }
    pay_pass.value = "";
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const goorderdet = (id) => {
  uni.navigateTo({
    url: "/pages/order/orderdet/index?id=" + id,
  });
};
const tkfun = (id) => {
  uni.navigateTo({
    url: "/pages/order/return/index?id=" + id,
  });
};

const shfun = (id) => {
  uni.navigateTo({
    url: "/pages/order/return/index?id=" + id + "&type=2",
  });
};

const gorefunddet = (id) => {
  uni.navigateTo({
    url: "/pages/order/returnwl/index?refund_id=" + id,
  });
};

const jcfun = (id) => {
  uni.navigateTo({
    url: "/pages/order/returndet/index?refund_id=" + id,
  });
};

const ifthfun = (item) => {
  let Array = item.some((item) => item.is_refund == 0);

  return Array;
};

// 定义 finish 方法
const finish = async (e) => {
  pay_pass.value = e;
  try {
    let res = await checkPayPass({ pay_pass: pay_pass.value });
    if (res.code == 200) {
      gepaymentfun();
    }
  } catch (e) {
    console.log(e);
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
  }
};
const forgot = () => {
  uni.navigateTo({
    url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
  });
};

const focusinput = ref(false);
</script>

<template>
  <view class="content">
    <view class="content-top">
      <view class="content-top-search">
        <up-search
          placeholder="商品名称/订单编号"
          v-model="pages.keyword"
          @search="searchfun"
          :showAction="false"
        ></up-search>
      </view>

      <view class="tbs-k">
        <up-tabs
          :activeStyle="{
            color: '#01ADA8',
            fontSize: '28rpx',
            fontWeight: 'bold',
            padding: '0 20rpx',
          }"
          lineColor="#01ADA8"
          :inactiveStyle="{
            color: '#8C8C8C',
            fontSize: '28rpx',
            padding: '0 20rpx',
          }"
          :list="listtabs"
          :current="current"
          @click="clicktabs"
        ></up-tabs>
      </view>
    </view>
    <view class="list" v-if="!isrefund">
      <!-- <view></view> -->
      <view class="list-item" v-for="(item, index) in list" :key="index">
        <view class="list-item-title">
          <view class="list-top-title">
            订单编号：{{ item.order_id }}
            <up-copy :content="item.order_id" @click.stop
              ><image src="@/static/cloudlibrary/copy-img.png" mode="widthFix"
            /></up-copy>
          </view>

          <text class="list-item-title" v-if="item.paid == 1">
            {{ item.status == 1 ? "待发货" : item.status_text }}
          </text>
          <text class="list-item-title" v-else-if="item.paid == 0">
            {{ item.status == 0 ? "待付款" : item.status_text }}
          </text>
          <text class="list-item-title" v-else> {{ item.paid_text }}</text>
        </view>
        <view
          class="list-item-content"
          v-for="(goods, index1) in item.orderProduct"
          :key="index1"
          @click="goorderdet(item.order_id)"
        >
          <view class="list-item-content-item">
            <view class="list-item-content-img">
              <image
                :src="goods.product_info ? goods.product_info.image : ''"
                mode=""
              ></image>
            </view>
            <view class="list-item-content-info">
              <view class="list-item-content-info-title">
                <view class="good-name">
                  <text>{{ goods.product_info.store_name }}</text>
                </view>
                <view>
                  <text class="good-name-mr">默认</text>
                </view>
              </view>
              <view class="list-item-price">
                <view>¥{{ formatPrice(goods.product_info.price) }}</view>
                <view class="good-name-num">x{{ goods.product_num }}</view>
                <view v-if="goods.is_refund != 0"
                  ><text class="good-name-text-index">{{
                    goods.refund_status_text
                  }}</text>
                </view>
              </view>
            </view>
          </view>
          <!-- <view class="list-item-content-item">
            <view class="list-item-content-img">
              <image src="/static/images/1.png" mode="widthFix"></image>
            </view>
            <view class="list-item-content-info">
              <view class="list-item-content-info-title">
                <view class="good-name">
                  <text>经销商升级大礼包套餐商升级大礼升级大礼升级...</text>
                </view>
                <view>
                  <text class="good-name-mr">默认</text>
                </view>
              </view>
              <view class="list-item-price">
                <view>¥2000</view>
                <view class="good-name-num">x1</view>
              </view>
            </view>
          </view> -->
        </view>
        <view class="list-nums">
          <text>共{{ item.total_num }}件, </text>
          <text>总计：</text
          ><text class="list-nums-s">¥{{ formatPrice(item.total_price) }}</text>
        </view>
        <view class="list-item-btn">
          <view
            class="list-item-btn-item-left"
            v-if="item.paid == 0"
            @click="canlfun(item.order_id, index)"
            >取消订单</view
          >
          <!-- <view
            class="list-item-btn-item-left"
            v-if="item.status == 1"
            @click="tkfun(item.order_id, index)"
            >退款</view
          > -->
          <!-- <view
            class="list-item-btn-item-left"
            v-if="item.status == 2"
            @click="shfun(item.order_id, index)"
            >售后</view
          > -->
          <view
            v-if="item.paid == 0"
            class="list-item-btn-item-right"
            @click="payfun(item, index)"
            >立即支付</view
          >
          <view
            v-if="item.status == 2 && ifthfun(item.orderProduct)"
            class="list-item-btn-item-right"
            @click="qrshfun(item.order_id, index)"
            >确认收货</view
          >

          <!-- <view
            v-if="item.status == 3"
            class="list-item-btn-item-right"
            @click="newpayfun(item.order_id, index)"
            >再来一单</view
          > -->
        </view>
      </view>
    </view>

    <view class="list" v-if="isrefund">
      <!-- <view></view> -->
      <view class="list-item" v-for="(item, index) in list" :key="index">
        <view class="list-item-title">
          <view class="list-top-title"
            >售后编号：{{ item.refund_id }}
            <up-copy :content="item.refund_id" @click.stop
              ><image
                src="@/static/cloudlibrary/copy-img.png"
                mode="widthFix" /></up-copy
          ></view>
          <text class="list-item-title" v-if="item.paid == 1">
            {{ item.status_text }}</text
          >
          <text class="list-item-title" v-else> {{ item.paid_text }}</text>
        </view>
        <view
          class="list-item-content"
          v-for="(goods, index1) in item.refundProduct"
          :key="index1"
          @click="gorefunddet(item.refund_id)"
        >
          <view class="list-item-content-item">
            <view class="list-item-content-img">
              <image
                :src="
                  goods.order_product_info ? goods.order_product_info.image : ''
                "
                mode=""
              ></image>
            </view>
            <view class="list-item-content-info">
              <view class="list-item-content-info-title">
                <view class="good-name">
                  <text>{{ goods.order_product_info.store_name }}</text>
                </view>
                <view>
                  <!-- 0:待审核 -1:审核未通过 -2全部 1:待退货 2:待收货 3:已退款 -->
                  <text class="good-name-mr">默认</text>
                </view>
              </view>
              <view class="list-item-price">
                <view>¥{{ formatPrice(goods.order_product_info.price) }}</view>
                <view class="good-name-num">x{{ goods.refund_num }}</view>
                <view
                  ><text class="good-name-text-index">{{
                    item.status_text
                  }}</text>
                </view>
              </view>
              <!-- <view
                class="list-item-btn-item-left-tx"
                v-if="goods.refund_type == 1"
                @click="@(item.order_id, index)"
                >待寄出</view
              > -->
            </view>
          </view>
          <!-- <view class="list-item-content-item">
            <view class="list-item-content-img">
              <image src="/static/images/1.png" mode="widthFix"></image>
            </view>
            <view class="list-item-content-info">
              <view class="list-item-content-info-title">
                <view class="good-name">
                  <text>经销商升级大礼包套餐商升级大礼升级大礼升级...</text>
                </view>
                <view>
                  <text class="good-name-mr">默认</text>
                </view>
              </view>
              <view class="list-item-price">
                <view>¥2000</view>
                <view class="good-name-num">x1</view>
              </view>
            </view>
          </view> -->
        </view>
        <view class="list-nums">
          <text>共{{ item.refund_num }}件, </text>
          <text>总计：</text
          ><text class="list-nums-s"
            >¥{{ formatPrice(item.refund_price) }}</text
          >
        </view>
        <view class="list-item-btn">
          <view
            v-if="item.status == 1"
            class="list-item-btn-item-right"
            @click="jcfun(item.refund_id, index)"
            >待寄出</view
          >
          <!-- <view
            v-if="item.status == 3"
            class="list-item-btn-item-right"
            @click="newpayfun(item.order_id, index)"
            >再来一单</view
          > -->
        </view>
      </view>
    </view>
  </view>

  <view class="nodeta" v-if="!loading && list.length <= 0">
    <image src="@/static/nodate/datas.png" mode="widthFix" />
  </view>

  <uni-load-more
    color="#c6c5c3"
    :status="status"
    v-if="!loading && list.length > 0"
  />

  <up-popup v-model:show="payshow" :round="10" @close="close">
    <view class="content-pay">
      <view
        class="content-pay-item"
        v-for="(item, index) in paylist"
        :key="index"
        @click="selectpayfun(item.title)"
      >
        <view
          :class="
            balance < total_price && item.title == 1
              ? 'content-pay-left noselect'
              : 'content-pay-left'
          "
        >
          <image :src="item.icon" mode="widthFix" />
          <text>{{ item.des }}</text>
          {{ item.title == 1 ? "(可用" + balance + "元)" : "" }}
        </view>
        <view class="content-pay-right" v-if="pay_type == item.title">
          <image src="@/pages/order/static/select.png" mode="widthFix" />
        </view>
      </view>
      <up-button
        @click="gopassword"
        class="custom-style"
        text="确认支付"
      ></up-button>
    </view>
  </up-popup>

  <!-- 取消订单弹框 -->
  <view class="password_show">
    <u-popup
      :show="showOrder"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="productGift">
        <view class="popup-content-title">温馨提示</view>
        <view class="popup-content-item"
          >取消订单无法回退，请确认取消订单？</view
        >
        <view class="popup-content-box">
          <view class="popup-content-bt">
            <view class="popup-content-qx" @click="closeOrder">取消</view>
            <view class="popup-content-cl" @click="orderSubmit">确定</view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>

  <!-- 密码弹框 -->
  <view class="password_show">
    <u-popup
      :show="showPassword"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="password">
        <view class="popup-content-title">支付密码</view>
        <u-code-input
          v-model="pay_pass"
          :maxlength="6"
          dot
          size="80"
          @change="onChange"
          @finish="finish"
          :focus="focusinput"
        ></u-code-input>
        <view class="footer">
          <view class="closefun" @click="showPassword = false">取消</view>
          <view class="forgot" @click="forgot">忘记密码？</view>
        </view>
      </view>
    </u-popup>
  </view>

  <!-- 确认收货弹框 -->
  <view class="password_show">
    <u-popup
      :show="showqrshfun"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="productGift">
        <view class="popup-content-title">温馨提示</view>
        <view class="popup-content-item">确认收货无法回退，是否确认收货？</view>
        <view class="popup-content-box">
          <view class="popup-content-bt">
            <view class="popup-content-qx" @click="closeqrshfun">取消</view>
            <view class="popup-content-cl" @click="qrshfunSubmit">确定</view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
